#include "time.h"

#include <pic18fregs.h>
#include <stdlib.h>

#include "HardwareProfile.h"

#include "lcd.h"

#define INCSPERSEC 300000

void setTime(Time* t, int offset)
{
	unsigned long totalSeconds = 0;

	t->hours = setNumber(24, offset + HRS_REL_OFFSET);
	totalSeconds += (unsigned long)t->hours * 3600;
	t->minutes = setNumber(60, offset + MIN_REL_OFFSET);
	totalSeconds += (unsigned long)t->minutes * 60;
	t->seconds = setNumber(60, offset + SEC_REL_OFFSET);
	totalSeconds += (unsigned long)t->seconds;

	t->totalSeconds = totalSeconds;
}

/*
* Get a number between 0 and range - 1.
* The user must use the buttons to select the number:
* 	Button0 -> Increment
* 	Button1 -> Confirm
*/
unsigned char setNumber(unsigned char range, int offset)
{
	unsigned char number = 0;
	char data[3];

	while(BUTTON1_IO == 1u)
	{
		if(BUTTON0_IO == 0u)
		{
			++number;
			number %= range;
			sprintf(data, "%02d", number);
			show(data, 2, offset);
		}
		while(BUTTON0_IO == 0u){}
	}
	while(BUTTON1_IO == 0u){}

	return number;
}

void waitMs(unsigned long ms)
{
	unsigned long incsPerMs = INCSPERSEC / 1000;
	unsigned long waitCycles = ms * incsPerMs;

	volatile unsigned long i;
	for(i = 0; i < waitCycles; i++){}
}

void updateTime(Time* time)
{
	unsigned long newSeconds = time->totalSeconds;

	time->hours = (unsigned char)(newSeconds / 3600);
	newSeconds %= 3600;
	time->minutes = (unsigned char)(newSeconds / 60);
	newSeconds %= 60;
	time->seconds = (unsigned char)(newSeconds);
}
